package com.blockmeta.bbs.immodule.activity.chat;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.net.callback.BaseResponseCallBack;
import com.blockmeta.bbs.baselibrary.net.callback.Callback;
import com.blockmeta.bbs.businesslibrary.arouter.RouterConstant;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseImResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.activity.CircleDetailActivity;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.corebean.ICircleDomainService;
import com.blockmeta.bbs.immodule.corebean.IMMetaBase;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.dao.ChatMessage;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.businesslibrary.widget.emoji.EmojiEditText;
import com.blockmeta.bbs.immodule.net.api.CircleMemberApi;
import com.blockmeta.bbs.immodule.net.pojo.CircleMemberResponse;
import com.blockmeta.bbs.immodule.utils.HanziToPinyin;
import com.blockmeta.bbs.immodule.widget.NoticeBar;
import com.blockmeta.bbs.immodule.widget.chatboard.InputFieldQueryAdapter;
import com.blockmeta.bbs.immodule.widget.chatboard.InputFieldQueryItem;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import io.reactivex.functions.BiConsumer;
import io.reactivex.functions.Consumer;
import rx.functions.Action1;

import static com.blockmeta.bbs.immodule.Constants.CALL_CHAR;

/**
 * Created by author on 2019/3/25.
 * 群聊天页面
 */
@Route(path = RouterPath.IM_UCGChatActivity_ACTIVITY, extras = RouterConstant.EXTRAL_LOGIN)
public class UCGChatActivity extends BaseChatActivity {
    //arouter注入bug，只能在子类
    @Autowired(name = Constant.ZERO)
    public String ZeroParam;

    ICircleDomainService circleDomainService;

    private List<Integer> callMeMsgLocations;
    protected List<CircleMemberResponse> mCircleMemberReponse;

    @BindView(R2.id.llayout_noticebar)
    NoticeBar mNoticeBar;

    @Override
    protected void initialize() {
        super.initialize();
        circleDomainService = IMApplicationContext.getCircleDomainService();
        mIvFriendOrCircleIcon.setImageResource(R.drawable.icon_to_circle);


    }

    private void getNoticeData() {
        mNoticeBar.onInitialize(this, toUserId, false);

    }

    @Override
    protected long getUserIdFromBundle() {
        if (!TextUtils.isEmpty(ZeroParam)) {
            return Long.parseLong(ZeroParam);
        } else {
            return getIntent().getLongExtra(Params.USER_TAG, 0);
        }
    }

    @Override
    void queryChatMsgData() {
        queryUnReadMsgs();

        //获取@在list中的位置
        bindButtonIfHasCallMeMsg();


        laterScrollToEnd();

    }

    /**
     * 递归消息，查找是否有人@我,改变按钮文字
     */
    private void bindButtonIfHasCallMeMsg() {
        final List<ChatMessage> data = mChatAdapter.getData();
        callMeMsgLocations = new ArrayList<>();
        for (int j = 0, dataSize = data.size(); j < dataSize; j++) {
            ChatMessage message = data.get(j);
            if (message.getChecked() == false && message.getContent().contains("im/user/" + AccountHelper.getUid())) {
                callMeMsgLocations.add(j);
            }
        }
        if (callMeMsgLocations.size() > 0) {
            m_txt_newmsg_backward.setText("有人@我");
            m_txt_newmsg_backward.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void scrollToNextMsgPoint(View v) {

        if (callMeMsgLocations.size() > 0) {
            int nextCallMeIndex = callMeMsgLocations.get(callMeMsgLocations.size() - 1);
            mRcvChatList.scollToPosition(nextCallMeIndex);
            callMeMsgLocations.remove(callMeMsgLocations.size() - 1);
            if (callMeMsgLocations.size() == 0) {
                if (m_unReadMSgIndex < nextCallMeIndex) {
                    //如果@点完后，还没有到未读的最上位置，就还是显示该按钮
                    m_unReadCount = nextCallMeIndex - m_unReadMSgIndex;
                    m_txt_newmsg_backward.setText(BaseApp.getApp().getString(R.string.social_im_newmsg_txt, m_unReadCount > 999 ? "999+" : String.valueOf(m_unReadCount)));
                } else {
                    v.setVisibility(View.GONE);
                }
            }
        } else {
            scrollToUnreadLocation(v);
        }
    }

    private void initKeyBoardData() {
        //已经获取过群成员不再获取
        if (mCircleMemberReponse != null && mCircleMemberReponse.size() > 0) {
            return;
        }

        IMApplicationContext.getCircleDomainService().getCircleMemberResponse(mContext, toUserId, false, new Action1<List<CircleMemberResponse>>() {
            @Override
            public void call(List<CircleMemberResponse> circleMemberResponses) {
                if (circleMemberResponses == null || circleMemberResponses.size() == 0) {
                    return;
                }
                mCircleMemberReponse = circleMemberResponses;
                //更新圈子的人数
                circleDomainService.updateCircleMemberCount(toUserId
                        , circleMemberResponses.size());
                IMApplicationContext.getIMMetaService().post(new IMMetaBase.Event_EditCircles(toUserId));
                mUser.setGroupCount(circleMemberResponses.size());
                bindGroupData();

                circleDomainService.addCircleMember(circleMemberResponses);

                HashSet<InputFieldQueryItem> tHashSet = new HashSet<>();
                int me = AccountHelper.getUidInt();
                for (CircleMemberResponse tUser : circleMemberResponses) {
                    if (tUser.getUserId() != me) {
                        IMUserEntity userEntity = mUserDomainService.getUser(tUser.getUserId(), Params.USER_PERSON);
                        if(userEntity != null){
                            String name = circleDomainService.getCircleRemarkName(userEntity, toUserId);

                            tHashSet.add(new InputFieldQueryItem(CALL_CHAR, tUser.getUserId() + "", name
                                    , CALL_CHAR + tUser.getUserId(), tUser.getAvatar(), userEntity.getName(),
                                    HanziToPinyin.getInstance().getLetter(name)));
                        }
                    }
                }

                mCbKeyboard.setSpecialInputListener(new EmojiEditText.SpecialInputListener() {
                    @Override
                    public void onChange() {
                        mCbKeyboard.showPopup(CALL_CHAR, CALL_CHAR);
                    }
                }, CALL_CHAR);

                mCbKeyboard.addType(CALL_CHAR, "[A-Za-z0-9.-_]*", InputFieldQueryAdapter.InputQueryItemMode.DETAIL_MULTI, tHashSet);

            }
        });
    }

    private void getCircleData() {
        circleDomainService.getGroup(toUserId, new BaseResponseCallBack<String, IMUserEntity>() {
            @Override
            public void fail(String msg) {

            }

            @Override
            public void success(IMUserEntity userEntity) {
                mUser = userEntity;
                //更新圈子人数并绑定@的列表
                initKeyBoardData();
                bindGroupData();
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mIsCreate) {
            mIsCreate = false;
            getCircleData();
            getNoticeData();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void bindGroupData() {
        if (mUser.getGroupCount() == 0) {
            mTvTitle.setText(mUser.getName());
        } else {
            mTvTitle.setText(String.format(Locale.getDefault(), "%s (%d)", mUser.getName(), mUser.getGroupCount()));
        }
    }


    @Override
    void jumpToFriendOrCircleHome() {
        Intent intent = new Intent(mContext, CircleDetailActivity.class);
        intent.putExtra(Params.CIRCLE_ID, toUserId);
        startActivity(intent);
    }


    @Override
    protected int getChatType() {
        return ChatMessage.MSG_TYPE_UCG;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_AddCircleNotice eventImMessage) {
        if(eventImMessage.mCircleId == toUserId){
            mNoticeBar.onInitialize(mContext, toUserId, true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_EditCircles event){
        if(event.circleId == toUserId) {
            getCircleData();
        }
    }
}
